<template>
	<view class="uni-container">
		<uni-forms ref="form" v-model="formData" validateTrigger="bind" @submit="submit">
			<uni-forms-item name="title" label="名称" required>
				<uni-easyinput v-model="formData.title" placeholder="请输入名称" />
			</uni-forms-item>
			<uni-forms-item name="path" label="图片地址" required>
				<uni-easyinput v-model="formData.path" :clearable="false" placeholder="请输入图片地址" />
			</uni-forms-item>
			<uni-forms-item name="type" label="请选择" required>
			    <radio-group v-model="formData.type" @change="e=>formData.type=e.detail.value">
			      <radio :value="0" :checked="formData.type === 0" style="margin-right: 20px;">打印机</radio>
			      <radio :value="1" :checked="formData.type === 1">小程序</radio>
			    </radio-group>
			</uni-forms-item>
			<uni-forms-item name="appid" label="小程序appid" required>
				<uni-easyinput v-model="formData.appid" :clearable="false" placeholder="请输入小程序appid" />
			</uni-forms-item>
			<uni-forms-item name="url" label="跳转地址" required>
				<uni-easyinput v-model="formData.url" :clearable="false" placeholder="请输入跳转地址" />
			</uni-forms-item>
			<view class="uni-button-group">
				<button style="width: 100px;" type="primary" class="uni-button"
					@click="submitForm">{{$t('common.button.submit')}}</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;"><button style="width: 100px;"
						class="uni-button">{{$t('common.button.back')}}</button></navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'banners';

	export default {
		data() {
			return {
				formData: {
					title: '',
					type: 0,
					path: "",
					appid: "",
					url: "",
				},
			}
		},
		methods: {
			/**
			 * 触发表单提交
			 */
			submitForm() {
				this.$refs.form.submit();
			},

			/**
			 * 表单提交
			 * @param {Object} event 回调参数 Function(callback:{value,errors})
			 */
			submit(event) {
				const {
					value,
					errors
				} = event.detail

				// 表单校验失败页面会提示报错 ，要停止表单提交逻辑
				if (errors) {
					return
				}
				uni.showLoading({
					title: '提交中...',
					mask: true
				})
				db.collection(dbCollectionName).add(value).then(res => {
					uni.showToast({
						title: '新增成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(err => {
					uni.hideLoading()
				})
			},
		}
	}
</script>
<style>
	::v-deep .uni-forms-item__label {
		width: 120px !important;
	}
</style>
